package day02;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/3/13 13:09
 * 力扣 Offer 32从上到下打印二叉树 III
 */
public class DequePractice {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) {
            return lists;
        }

        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int c1 = 1;
        boolean flag = true;
        while(!queue.isEmpty()) {
            LinkedList<Integer> list = new LinkedList<>();
            int c2 = 0;
            for (int i = 0; i < c1; i++) {
                TreeNode p = queue.poll();
                if (flag) {
                    list.addLast(p.val);
                } else {
                    list.addFirst(p.val);
                }
                if (p.left != null) {
                    queue.offer(p.left);
                    c2++;
                }
                if (p.right != null) {
                    queue.offer(p.right);
                    c2++;
                }
            }
            c1 = c2;
            flag = !flag;
            lists.add(list);
        }
        return lists;
    }
}
